/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 UJF.
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */

package org.osami.gateway.sensor.proxy;

import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONObject;
import org.osami.gateway.sensor.Sense;
import org.osami.gateway.sensor.SenseData;
import org.osami.gateway.sensor.SenseNode;
import org.osami.gateway.tools.JsonRestTools;

public final class SenseProxy implements Sense {

    private final String name;

    private final String topic;

    private final String nodeId;

    private final String myurl;

    private final String sensid;

    protected SenseProxy(final String pName, final String url, final SenseNode pNode) {
        name = pName;
        nodeId = pNode.getId();
        topic = pNode.getTopic() + name;
        myurl = url + SenseNode.DATA_RESSOURCE_NAME + "/" + name;
        sensid = nodeId + name;
    }

    public SenseData getData() {
        String request = null;
        try {
            request = JsonRestTools.doGet(myurl);
            JSONObject jobj = new JSONObject(request);
            return new SenseDataJson(jobj, sensid);
        } catch (MalformedURLException me) {
            throw new RuntimeException("Cannot get data on sense, Bad request url: " + myurl, me);
        } catch (IOException ie) {
            throw new RuntimeException("Cannot get data on sense, IOException \n" + ie.getMessage(), ie);
        } catch (Exception je) {
            throw new RuntimeException("Cannot get data on sense, bad data: " + request, je);
        }
    }

    public String getNodeId() {
        return nodeId;
    }

    public String getTopic() {
        return topic;
    }

    public String getName() {
        return name;
    }
}
